// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const {ccclass, property} = cc._decorator;

@ccclass
export default class btnMoveAction extends cc.Component {

    @property({displayName : "最大宽度"})
    maxWidth : cc.Vec2 = cc.v2(0,0);

    @property()
    isLine : boolean = true;

    initData = null;

    initPos = null;

    protected onLoad(): void {
        this.node.on("touchstart",this.TouchStart,this);
        this.node.on("touchmove",this.TouchMove,this);
        this.node.on("touchend",this.TouchEnd,this);
        this.node.on("touchcancel",this.TouchEnd,this);
        this.node.getChildByName("btn").on("touchstart",this.clickUse,this);
        this.node.getChildByName("btn").on("touchend",this.noClickUse,this);
        this.node.getChildByName("btn").on("touchcancel",this.noClickUse,this);
    }

    isClick = false;
    clickUse(event){
        this.isClick = true;
    }

    noClickUse(event){
        this.isClick = false;
    }

    isClickArea = false;
    TouchStart(event){
        if(!this.isClick) return;
        this.isClickArea = true;
        let pos  = this.node.convertToNodeSpaceAR(event.getLocation());
        this.initPos = cc.v2(pos.x,pos.y);
    }

    TouchMove(event){
        if(!this.isClick) return;
        let pos = this.node.convertToNodeSpaceAR(event.getLocation());
        let pos1 = pos.sub(this.initPos);
        let pos2 = cc.v2(this.node.getChildByName("btn").x,this.node.getChildByName("btn").y);
        let pos3 = pos2.add(pos1);
        if(this.isLine){
            if( pos3.x <= this.maxWidth.x){
                pos3.x = this.maxWidth.x;
            }else if(pos3.x >= this.maxWidth.y){
                pos3.x = this.maxWidth.y;
            }else{
                this.node.getChildByName("btn").x = pos3.x;
            }
        }else{
            if( pos3.y <= this.maxWidth.x){
                pos3.y = this.maxWidth.y;
            }else if(pos3.y >= this.maxWidth.y){
                pos3.y = this.maxWidth.y;
            }else{
                this.node.getChildByName("btn").y = pos3.y;
            }
        }
        this.initPos = pos;
    }

    TouchEnd(event){
        if(!this.isClick && !this.isClickArea) return;
        this.isClickArea = false;
    }

}


